<template>
	<!-- 遮罩层和弹窗 -->
	<view v-if="visible" class="modal-mask" @touchmove.stop.prevent>
		<view class="login-modal">
			<!-- 登录模块 -->
			<view v-if="!showRegister">
				<view class="modal-header">
					<view class="modal-tabs">
						<text :class="['modal-tab', loginTab === 0 ? 'active' : '']" @click="loginTab = 0">账号登录</text>
						<text :class="['modal-tab', loginTab === 1 ? 'active' : '']" @click="loginTab = 1">微信授权登录</text>
					</view>
					<text class="modal-close" @click="handleClose">×</text>
				</view>
				<view class="modal-body">
					<view v-if="loginTab === 0" style="width: 100%;">
						<input class="modal-input" placeholder="用户名/手机号" v-model="loginForm.username" />
						<input class="modal-input" placeholder="密码" type="password" v-model="loginForm.password" />
					</view>
					<!-- <view v-else>
						<input class="modal-input" placeholder="手机号" v-model="loginForm.phone" />
						<input class="modal-input" placeholder="短信验证码" v-model="loginForm.sms" />
					</view> -->
					<view class="modal-btn-row" v-if="loginTab === 0">
						<button class="modal-btn primary" @click="handleLogin">登录</button>
						<button class="modal-btn" @click="handleClose">取消</button>
					</view>
					<view class="modal-btn-row-wechat" v-else>
						<button class="modal-btn weChat" @click="toLog">
							<image src="/static/WeChat_icon.png" mode="aspectFill" style="width: 40rpx;height: 40rpx;margin-right: 10rpx;"></image>
							微信授权登录
						</button>
					</view>
					<view class="modal-footer-row">
						<text class="modal-link" @click="showRegisterForm">免费注册用户</text>
						<!-- <text class="modal-link right">忘记密码?</text> -->
					</view>
				</view>
			</view>
			
			<!-- 注册模块 -->
			<view v-else>
				<view class="modal-header">
					<view class="modal-tabs">
						<text class="modal-tab active">用户注册</text>
					</view>
					<text class="modal-close" @click="handleClose">×</text>
				</view>
				<view class="modal-body">
					<input class="modal-input" placeholder="昵称" v-model="registerForm.nickname" />
					<input class="modal-input" placeholder="手机号" v-model="registerForm.phone" />
					<input class="modal-input" placeholder="密码" type="password" v-model="registerForm.password" />
					<input class="modal-input" placeholder="确认密码" type="password" v-model="registerForm.confirmPassword" />
					<view class="modal-btn-row">
						<button class="modal-btn primary" @click="handleRegisterSubmit">提交注册</button>
						<button class="modal-btn" @click="showLoginForm">返回登录</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
// import type { LoginForm, RegisterForm } from '@/utils/types'
import { register, login, getUserInfo, logout, scanLogin, oaLogin, oaAuthBind } from '@/api/user.js';
	import { setToken, getToken } from '@/utils/token.js';
// 登录表单类型
export interface LoginForm {
  username: string
  password: string
  phone: string
  sms: string
}

// 注册表单类型
export interface RegisterForm {
  nickname: string
  phone: string
  password: string
  confirmPassword: string
}

// Props
interface Props {
	visible: boolean
}

const props = defineProps<Props>()

// Emits
interface Emits {
	close: []
	login: [formData: LoginForm]
	register: []
	registerSuccess: [userData: any]
}

const emit = defineEmits<Emits>()

// 响应式数据
const loginTab = ref<number>(0)
const showRegister = ref<boolean>(false)
const loginForm = reactive<LoginForm>({
	username: '',
	password: '',
	phone: '',
	sms: ''
})
const registerForm = reactive<RegisterForm>({
	nickname: '',
	phone: '',
	password: '',
	confirmPassword: ''
})

// 方法
const handleClose = (): void => {
	showRegister.value = false
	resetForms()
	emit('close')
}

const handleLogin = (): void => {
	emit('login', { ...loginForm })
}

const showRegisterForm = (): void => {
	showRegister.value = true
}

const showLoginForm = (): void => {
	showRegister.value = false
}

const resetForms = (): void => {
	// 重置登录表单
	loginForm.username = ''
	loginForm.password = ''
	loginForm.phone = ''
	loginForm.sms = ''
	
	// 重置注册表单
	registerForm.nickname = ''
	registerForm.phone = ''
	registerForm.password = ''
	registerForm.confirmPassword = ''
}

// 验证注册表单
const validateRegisterForm = (): boolean => {
	if (!registerForm.nickname.trim()) {
		uni.showToast({
			title: '请输入昵称',
			icon: 'none'
		})
		return false
	}
	
	if (!registerForm.phone.trim()) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return false
	}
	
	// 简单的手机号验证
	const phoneRegex = /^1[3-9]\d{9}$/
	if (!phoneRegex.test(registerForm.phone)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return false
	}
	
	if (!registerForm.password.trim()) {
		uni.showToast({
			title: '请输入密码',
			icon: 'none'
		})
		return false
	}
	
	if (registerForm.password.length < 6) {
		uni.showToast({
			title: '密码长度不能少于6位',
			icon: 'none'
		})
		return false
	}
	
	if (registerForm.password !== registerForm.confirmPassword) {
		uni.showToast({
			title: '两次输入的密码不一致',
			icon: 'none'
		})
		return false
	}
	
	return true
}

// 处理注册提交
const handleRegisterSubmit = async (): Promise<void> => {
	if (!validateRegisterForm()) {
		return
	}
	
	try {
		// 调用注册接口
		const registerParams = {
			account: registerForm.phone,
			password: registerForm.password,
			nickname: registerForm.nickname,
			terminal: 3
		}
		
		const registerResult = await register(registerParams)
		
		if (registerResult.code === 1) {
			uni.showToast({
				title: '注册成功',
				icon: 'success'
			})
			
			// 注册成功后自动登录
			const loginParams = {
				account: registerForm.phone,
				password: registerForm.password,
				terminal: 3
			}
			
			const loginResult = await login(loginParams)
			
			if (loginResult.code === 1) {
				// 登录成功，触发事件
				emit('registerSuccess', loginResult.data)
				resetForms()
				showRegister.value = false
				emit('close')
			} else {
				uni.showToast({
					title: loginResult.msg || '自动登录失败，请手动登录',
					icon: 'none'
				})
				// 注册成功但登录失败，切换到登录界面
				showRegister.value = false
			}
		} else {
			uni.showToast({
				title: registerResult.msg || '注册失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('注册失败:', error)
		uni.showToast({
			title: '注册失败，请重试',
			icon: 'none'
		})
	}
}

const handleRegister = (): void => {
	emit('register')
}

const userInfo = ref({})
const toLog = () => {
	// return
	let code = getQueryVariable('code')
	if (code) {
		console.log(code);
		oaLogin({code}).then(res=>{
			console.log(res)
			if(res.code == 1){
				setToken(res.data.token)
				uni.setStorageSync('userInfo', res.data)
				uni.setStorageSync('user_id', res.data.id)
				userInfo.value = res.data
			}
		}).catch(error=>{
			console.log(error)
		})
	} else {
		console.log('111111111111111111111111111111')
		let appid = "wx36819d0881150fc8" //项目appid
		let mainstate = Math.random()
		let url = encodeURIComponent('https://cqjsyh.com/H5') //这里的是回调地址要与申请的地址填写一致
		let scopes = "snsapi_userinfo" //表示授权的作用域，多个可以用逗号隔开，snsapi_base表示静默授权，snsapi_userinfo表示非静默授权
		let httpsUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=${scopes}&state=${mainstate}&connect_redirect=1#wechat_redirect`
		window.location.href = httpsUrl
	}
}

const getQueryVariable = (variable) => {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return (false);
}
</script>

<style scoped>
/* .modal-mask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.login-modal {
	width: 80%;
	max-width: 400px;
	background-color: white;
	border-radius: 10px;
	overflow: hidden;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #eee;
}

.modal-tabs {
	display: flex;
	gap: 20px;
}

.modal-tab {
	padding: 8px 16px;
	border-radius: 20px;
	background-color: #f5f5f5;
	color: #666;
	font-size: 14px;
	cursor: pointer;
	transition: all 0.3s;
}

.modal-tab.active {
	background-color: #007aff;
	color: white;
}

.modal-close {
	font-size: 24px;
	color: #999;
	cursor: pointer;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-body {
	padding: 20px;
}

.modal-input {
	width: 100%;
	height: 45px;
	border: 1px solid #ddd;
	border-radius: 5px;
	padding: 0 15px;
	margin-bottom: 15px;
	font-size: 16px;
	box-sizing: border-box;
}

.modal-input:focus {
	border-color: #007aff;
	outline: none;
}

.modal-btn-row {
	display: flex;
	gap: 10px;
	margin-top: 20px;
}

.modal-btn {
	flex: 1;
	height: 45px;
	border: 1px solid #ddd;
	border-radius: 5px;
	background-color: white;
	color: #333;
	font-size: 16px;
	cursor: pointer;
}

.modal-btn.primary {
	background-color: #007aff;
	color: white;
	border-color: #007aff;
}

.modal-footer-row {
	display: flex;
	justify-content: space-between;
	margin-top: 15px;
}

.modal-link {
	color: #007aff;
	font-size: 14px;
	cursor: pointer;
}

.modal-link.right {
	margin-left: auto;
} */
 .modal-mask {
	position: fixed;
	z-index: 9999;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: center;
	justify-content: center;
}

.login-modal {
	width: 400px;
	max-width: 90vw;
	background: #fff;
	border-radius: 12px;
	box-shadow: 0 4px 24px rgba(0, 0, 0, 0.18);
	padding: 0 0 24px 0;
	position: relative;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 24px;
	height: 56px;
	border-bottom: 1px solid #f5e3c2;
	background: #fdf6e3;
	border-radius: 12px 12px 0 0;
}

.modal-tabs {
	display: flex;
	align-items: center;
}

.modal-tab {
	font-size: 18px;
	color: #b98c4b;
	padding: 0 16px;
	line-height: 56px;
	cursor: pointer;
}

.modal-tab.active {
	color: #e69c23;
	font-weight: bold;
	border-bottom: 2px solid #e69c23;
}

.modal-close {
	font-size: 28px;
	color: #b98c4b;
	cursor: pointer;
	margin-left: 12px;
}

.modal-body {
	width: 100%;
	padding: 24px 32px 0 32px;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
}

.modal-input {
	width: 100%;
	height: 40px;
	margin-bottom: 16px;
	border: 1px solid #e5e5e5;
	border-radius: 4px;
	padding: 0 12px;
	box-sizing: border-box;
	font-size: 16px;
	background: #fafafa;
}

.modal-btn-row {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	margin-top: 8px;
	gap: 12px;
}

.modal-btn {
	min-width: 90px;
	height: 36px;
	border-radius: 4px;
	border: none;
	font-size: 16px;
	background: #f5f5f5;
	color: #666;
	margin-right: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-btn.primary {
	background: #ffb43a;
	color: #fff;
}

.modal-footer-row {
	display: flex;
	/* justify-content: space-between; */
	justify-content: flex-end;
	align-items: center;
	margin-top: 12px;
	padding: 0 2px;
}

.modal-link {
	font-size: 14px;
	color: #b98c4b;
	cursor: pointer;
}

.modal-link.right {
	float: right;
}
</style>